package com.alan.product.issue.stack;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class StackOverFlowTest {
    // -Xss10k
    public static void main(String[] args) throws InterruptedException, IOException {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();

        thread1.start();
        thread2.start();

        thread1.queue.put(() -> test1(0));
        thread2.queue.put(() -> test1(1));

        thread1.queue.put(() -> System.out.println("thread1 finished"));
        thread2.queue.put(() -> System.out.println("thread2 finished"));

        System.out.println("main");

        System.in.read();
    }

    private static void test1(int i) {
        System.out.println(i);
        if (i % 2 == 0) {
            if (i < 10) {
                test1(i + 2);
            }
        } else {
            test2(i + 2);
        }
    }

    private static void test2(int i) {
        test1(i + 2);
    }

    static class MyThread extends Thread {
        private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

        @Override
        public void run() {
            while (true) {
                try {
                    Runnable command = queue.take();
                    command.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
